<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>

    <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="enumList"></EnumSlot>
    </template>

    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>

    <template v-slot:table>
      <TableData v-if="!searchFormData.dealFlag" :config="table_config" :tableThead="tableThead" :dataList="dataList"
        :loading="loading" @selection-change="selectionChange">
        <template v-slot:batchName="{ row }">
          {{ batchObj[row.batchId] }}
        </template>
      </TableData>
      <TableData v-if="!!searchFormData.dealFlag && !searchFormData.completeFlag" :config="{ isOperation: false }"
        :tableThead="tableThead" :dataList="dataList" :loading="loading" @selection-change="selectionChange">
        <template v-slot:batchName="{ row }">
          {{ batchObj[row.batchId] }}
        </template>
      </TableData>
      <TableData v-if="searchFormData.dealFlag && searchFormData.completeFlag" :config="table_config_completeFlag"
        :tableThead="tableThead" :dataList="dataList" :loading="loading" @selection-change="selectionChange">

        <template v-slot:batchName="{ row }">
          {{ batchObj[row.batchId] }}
        </template>
      </TableData>
    </template>

    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size"   @current-change="handleCurrentChange" :page="page" :total="total">
      </Pagination>
    </template>

    <template v-slot:dialogModule>
      <AddEdit :title="'疾病记录'" @closeDialog="closeDialog" :diseaseList="diseaseList" :batchList="batchList"
        :facilityList="facilityList" :varietyList="varietyList" :addEditFlag="addEditFlag"
        :dialogVisible="dialogVisible" :data="formData">
      </AddEdit>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import SearchForm from '@/components/SearchForm';
import TableData from '@/components/TableData';
import BtnSlot from '@/components/BtnSlot';
import EnumSlot from '@/components/EnumSlot';
import AddEdit from './components/addEdit.vue';
import diseaseRecord from '@/api/healthManagement/diseaseRecord.js';
import diseaseManagement from '@/api/diseaseBankManagement/diseaseManagement.js';
import specificationManagement from '@/api/basicInformation/specificationManagement.js';
import facilityManagement from '@/api/digtalOperation/facilityManagement.js';
import varietyManagement from '@/api/basicInformation/varietyManagement.js';
import batch from '@/api/batch/batchManagement';

export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, AddEdit },
  data() {
    return {
      resetTable: false,
      unfoldFlag: false,
      loading: false,
      dialogVisible: false,
      viewFlag: false,
      addEditFlag: 'add',
      formData: {},
      batchObj: {},
      searchFormData: {
        dealFlag: false,
        completeFlag: false,
      },
      page: 1,
      size:10,
      total: 199,
      selectIndex: 0,
      btnList: ['add', 'delete'],
      enumList: [{
        label: "未处理",
        id: 1,
        flag: 'dealFlag',
      },
      {
        label: "已处理",
        id: 2,
        flag: 'dealFlag',
      },
      {
        label: "已完成",
        id: 3,
        flag: 'completeFlag'
      }],
      dataList: [],
      tableThead: [
        { isShow: true, label: '疾病名称', prop: 'diseaseName' },
        { isShow: true, label: '发现疾病设施', prop: 'facilityName' },
        { isShow: true, label: '批次名称', slotName: 'batchName' },
        { isShow: true, label: '患病品种', prop: 'plantVarietyName' },
        { isShow: true, label: '患病粒数', prop: 'num' },
        { isShow: true, label: '上报人', prop: 'staffName' },
        { isShow: true, label: '发现时间', prop: 'happenTime' }
      ],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '编辑',
              type: 'primary',
              flag: 'edit',
              handleRow: this.handleRow
            },
            {
              label: '删除',
              type: 'danger',
              flag: 'delete',
              handleRow: this.handleRow
            }
          ]
        },
      },
      // 配置项
      table_config_completeFlag: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '删除',
              type: 'danger',
              flag: 'delete',
              handleRow: this.handleRow
            }
          ]
        },
      },
      varietyList: [],
      facilityList: [],
      batchList: [],
      specificationList: [],
      diseaseList: [],
      formItemList: [
        {
          label: '养殖设施',
          type: 'select',
          selectOptions: [],
          param: 'facilityId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '批次名称',
          type: 'select',
          selectOptions: [],
          param: 'batchId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '上报人',
          type: 'select',
          selectOptions: [],
          param: 'staffName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '发现日期',
          type: 'datetimerange',
          param: 'dateTime',
          multiple: false,
          isShow: true
        }
      ]
    }
  },

  computed: {
    person() {
      return this.$store.state.initData.person || [];
    },
  },
  mounted() {
    this.queryPageByCondition();
    this.initData();
  },
  methods: {
    async initData() {
      let { data: diseaseList } = await diseaseManagement.queryByCondition({})
      this.diseaseList = diseaseList
      let { data: specificationList } = await specificationManagement.queryByCondition({});
      this.specificationList = specificationList;
      // 获取批次列表 
      let { data: batchList } = await batch.queryByCondition({ batchType: 'BREEDING' });
      this.batchList = batchList;
      this.batchObj = {};
      this.batchList.forEach(item => {
        this.batchObj[item.batchId] = item.batchName
      })
      //获取品种；
      let { data: varietyList } = await varietyManagement.queryByCondition({})
      this.varietyList = varietyList || [];
      //获取养殖设施；
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      this.facilityList = facilityList || [];
      this.setFormOptions();
    },

    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('facilityId') !== -1) {
          console.log(this.facilityList)
          let selectOptions = this.facilityList.map(data => {
            return {
              text: data.facilityName, value: data.facilityId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('batchId') !== -1) {
          let selectOptions = this.batchList.map(data => {
            return {
              text: data.batchName, value: data.batchId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param == 'staffName') {
          let selectOptions = this.person.map(data => {
            return {
              text: data.person.name, value: data.person.name
            }
          })
          item.defaultSelect = this.searchFormData[item.param]
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    //获取选中Enum
    getEnumEvent(enumInfo) {
      this.page = 1;
      this.selectIndex = enumInfo.index || 0;
      console.log(enumInfo.data.id)
      if (enumInfo.data.id == 1) {
        this.$set(this.searchFormData, 'dealFlag', false);
        this.$set(this.searchFormData, 'completeFlag', false);
      } else if (enumInfo.data.id == 2) {
        this.$set(this.searchFormData, 'dealFlag', true);
        this.$set(this.searchFormData, 'completeFlag', false);
      } else if (enumInfo.data.id == 3) {
        this.$set(this.searchFormData, 'dealFlag', true);
        this.$set(this.searchFormData, 'completeFlag', true);
      }
      this.enunLabel = enumInfo.data.label
      this.queryPageByCondition();
    },
    // diseaseManagement
    delList(deleteList = [], key = 'diseaseRecordId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      console.log(list)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await diseaseRecord.delList(list);
        if (res.code == 1) {
          this.$message.success(res.msg || '删除成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData
        }
      }
      this.resetTable = false;
      diseaseRecord.queryPageByCondition(params).then(res => {
        this.resetTable = true;
        if (res.code == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    search(data) {
      this.page = 1;
      let endData = null;
      let startData = null;
      if (data.dateTime && data.dateTime.length == 2) {
        startData = `${data.dateTime[0]} 00:00:00`;
        endData = `${data.dateTime[1]} 23:59:59`;
      }
      this.searchFormData = {
        ...this.searchFormData,
        ...data,
        endTime: endData,
        startTime: startData
      };
      this.queryPageByCondition();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == 'edit') {
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData))
      } else if (item.flag == 'delete') {
        this.delList([rowData]);
      }
      this.addEditFlag = item.flag
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.dialogVisible = true
      } else if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
      this.addEditFlag = flag
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
    },
  }
};
</script>

<style lang="scss" scoped>
.pointer {
  cursor: pointer;
}
</style>